<template>
    <div class="amap">
      <!-- 地图容器 -->
      <div ref="amap" class="amap_view"></div>
      <!-- 搜索栏 -->
      <el-input
        id="map_input"
        v-model.trim="searchVal"
        placeholder="请输入关键字"
        size="small"
      ></el-input>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        searchVal: "",
        map: null,
      };
    },
    mounted() {
      this.loadAMap();
    },
    beforeDestroy() {
      if (this.map) {
        this.map.destroy();
        this.map = null;
      }
    },
    methods: {
      loadAMap() {
        const AMapLoader = require("@amap/amap-jsapi-loader");
        AMapLoader.load({
          key: "857e8d2b7941c47485a8a0092075685f", // Web端JS API key
          version: "2.0",
          plugins: ["AMap.Scale", "AMap.ToolBar"],
        })
          .then((AMap) => {
            this.initMap(AMap);
          })
          .catch((e) => {
            console.error(e);
          });
      },
      initMap(AMap) {
        this.map = new AMap.Map(this.$refs.amap, {
          resizeEnable: true, // 城市定位
          zooms: [1, 18],
          zoom: 14,
        });
  
        // 比例尺
        this.map.addControl(new AMap.Scale());
        // 工具条
        this.map.addControl(new AMap.ToolBar());
  
        // 标记
        let maker = new AMap.Marker({
          title: "长安街1号",
          position: this.map.getCenter(),
        });
        this.map.add(maker);
  
        // 关键字搜索
        AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], () => {
          let auto = new AMap.AutoComplete({ input: "map_input" });
          let placeSearch = new AMap.PlaceSearch({ map: this.map }); // 构造地点查询类
          // 注册监听，当选中某条记录时会触发
          auto.on("select", (e) => {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name); // 关键字查询查询
          });
        });
      },
    },
  };
  </script>
  
  <style scoped>
  
  
  </style>